package com.yanqu.road.server.cmd.tradewar;

import com.yanqu.road.logic.pb.BattlePb;
import com.yanqu.road.logic.pb.PatronsPb;
import com.yanqu.road.entity.config.battle.BattleResult;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.tradewar.UserTradeWarBattle;
import com.yanqu.road.pb.patrons.PatronsProto;
import com.yanqu.road.pb.tradewar.TradeWarProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.TradeWarModule;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.server.command.Cmd;

@Cmd(code = Protocol.S_TRADE_WAR_BATTLE_START, desc = "开战")
public class TradeWarBattleStartCmd extends AbstractCommand {

	private BattleResult result;

	private long nowTime;

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		nowTime = System.currentTimeMillis();
		UserTradeWarBattle userTradeWarBattle = player.getModule(TradeWarModule.class).getUserTradeWarBattle();
		if(null == userTradeWarBattle){
			ret = GameErrorCode.E_SYSTEM_NO_OPEN;
			return;
		}
		if(userTradeWarBattle.getEnemyUserId() == 0 || userTradeWarBattle.getPatronsList().size() <= 0){
			ret = GameErrorCode.E_TRADE_WAR_NO_PREPARE;
			return;
		}
		result = player.getModule(TradeWarModule.class).battleStart();
	}

	@Override
	public void sendData(GamePlayer player) {
		TradeWarProto.TradeWarBattleStartRespMsg.Builder respMsg = TradeWarProto.TradeWarBattleStartRespMsg.newBuilder();
		respMsg.setRet(ret);
		if (0 == ret && null != result) {
			//战斗详细信息
			respMsg.setBattleDetailList(BattlePb.parseBattleDetailListMsg(result.getPatronsBattleDetailList()));
			//我方出战门客
			respMsg.addAllPatronsIdList(result.getMyPatronsIdList());
			//对手出战门客
			for (UserPatrons userPatrons : result.getEnemyPatronsList()) {
				PatronsProto.PatronsTempMsg.Builder patronsMsg = PatronsPb.parsePatronsTempMsg(userPatrons);
				if(null != patronsMsg) {
					respMsg.addEnemyPatronsList(patronsMsg);
				}
			}
			respMsg.setKillPatronsCount(result.getKillPatronsCount());
			respMsg.setMyAddScore(result.getMyAddScore());
			respMsg.setEnemyLoseScore(result.getEnemyLoseScore());
			respMsg.setReward(result.getReward());
			respMsg.setEffectMammonSkill(result.getEffectMammonSkill());
			respMsg.setAddEarnSpeed(result.getAddEarnSpeed().intValue());
			respMsg.setUseItemId(result.getUseItemId());
			respMsg.setWarTimes(result.getWarTimes());
		}
		player.sendPacket(Protocol.U_TRADE_WAR_BATTLE_START, respMsg);
		log.info("trade war battle cost time:{}", System.currentTimeMillis() - nowTime);
	}
}
